﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace Expressionista.UserControls
{
	/// <summary>
	/// Interaction logic for MatchesView.xaml
	/// </summary>
	public partial class MatchesView : UserControl
	{
		public MatchesView()
		{
			InitializeComponent();
		}



		internal void SetMatches(string regexStr, RegexOptions options, string source)
		{
			Regex regex = null;

			try
			{
				regex = new Regex(regexStr, options);
			}
			catch (Exception e)
			{
				MatchesTV.BeginInit();
				MatchesTV.Items.Clear();
				MatchesTV.Items.Add(string.Format("Error processing Regex: {0}", e));
				MatchesTV.EndInit();
				return;
			}

			MatchCollection matchCollection = regex.Matches(source);

			MatchesTV.BeginInit();
			MatchesTV.Items.Clear();

			if (matchCollection == null || matchCollection.Count < 1)
			{
				MatchesTV.Items.Add("No matches found.");
				MatchesTV.EndInit();
				return;
			}

			foreach (Match m in matchCollection)
			{
				TreeViewItem tvi = new TreeViewItem();
				tvi.Header = string.Concat("[Match] : ", m.Value);
				tvi.Width = double.NaN;
				tvi.IsExpanded = true;

				for (int i = 1; i < m.Groups.Count; i++)
				{
					TreeViewItem matchTVI = new TreeViewItem();
					string groupName = regex.GroupNameFromNumber(i);
					string groupVal = m.Groups[i].Value;
					matchTVI.Header = string.Format("[{0}] : {1}", groupName, groupVal);
					matchTVI.Width = double.NaN;
					matchTVI.Background = Brushes.Ivory;
					tvi.Items.Add(matchTVI);
				}

				MatchesTV.Items.Add(tvi);
			}
			MatchesTV.EndInit();
		}
	}
}
